<?php

namespace App\Http\Middleware;

use App\Model\Admin;
use Closure;

class CheckAdminToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('Authorization');
        $admin = Admin::select('sf_admin.*', 'sf_role.role')->where('token', $token)->leftJoin('sf_role', 'sf_admin.role_id', '=', 'sf_role.id')->first();
        $nowTime = millisecond();
        $tokenAlive = 3600 * 24 * 2 * 1000; // 2天过期
        if ($admin) {
            if ($nowTime - $admin->last_login_time > $tokenAlive) {
                // token 过期
                return resJson(401);
            } else if ($nowTime - $admin->last_login_time > $tokenAlive / 2) {
                // 时间过去一半，更新时间，不再更新token，麻烦的很
                $admin = Admin::find($admin->id);
                $admin->last_login_time = $nowTime;
                $admin->save();
            }
            $request->_admin = $admin; // 注入用户信息
            return $next($request);
        } else {
            return resJson(403);
        }
    }
}
